﻿using Rhino;
using Rhino.PlugIns;
using System;
using System.IO;
using System.Linq;

namespace AiMoInGH.Connector
{
    static class AiMoRhinoLoader
    {
        public static string CurrentAiMoGHALocation
        {
            get
            {
                return Grasshopper.Instances.ComponentServer.Libraries
                    .FirstOrDefault(x => x.Name == "AiMoInGH")
                    ?.Location ?? "";
            }
        }
        public static bool HasRhinoAiMoInstalled(out string exeFile)
        {
            PlugInInfo info = PlugIn.GetPlugInInfo(new Guid("38d7b5db-b410-4490-b7b3-6bd7c21dfd0a"));
            string aimoFolder = "";
            if (info == null)
            {
                string ghaFilePath = CurrentAiMoGHALocation;
                string possibleAiMoRhpPath = CurrentAiMoGHALocation.Replace("AiMoInGH.gha", "AiMo3D.rhp");
                if (File.Exists(possibleAiMoRhpPath))
                {
                    RhinoApp.InvokeOnUiThread(new Action(() => { TryLoadAiMoRhp(possibleAiMoRhpPath); }), null);
                }
                aimoFolder = Path.GetDirectoryName(ghaFilePath);
            }
            else
            {
                aimoFolder = Path.GetDirectoryName(info.FileName);
            }

            exeFile = Path.Combine(aimoFolder, "lib", "AiMoWindows.exe");
            bool re = File.Exists(exeFile);
            if (!re)
            {
                Eto.Forms.MessageBox.Show($"Cannot find AiMo Editor (AiMoWindows.exe) in the AiMo Folder:\n{aimoFolder}.\nThe aimo plugin may missing files, please re-install AiMo");
            }
            return re;
        }

        static void TryLoadAiMoRhp(string rhp)
        {
            PlugIn.LoadPlugIn(rhp, out _);
        }
    }
}
